package com.ltg.widget;

import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;

import com.ltg.topactivity.R;

public class RelativeSizeView extends ViewGroup {
  private float relativeSize = 1;

  public RelativeSizeView(Context context, AttributeSet attrs) {
    super(context, attrs);
    TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.RelativeSizeView);
    setRelativeSize(a.getFloat(0, relativeSize));
    a.recycle();
  }

  public RelativeSizeView(Context context) {
    this(context, null);
  }

  public void setRelativeSize(float size) {
    relativeSize = size;
  }

  public float getRelativeSize() {
    return relativeSize;
  }

  @Override
  public void addView(View child, int index, ViewGroup.LayoutParams params) {
    if (getChildCount() > 0) { throw new IllegalStateException("RelativeSizeView can host only one direct child"); }

    super.addView(child, index, params);
  }

  @Override
  protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    int widthMode = MeasureSpec.getMode(widthMeasureSpec);
    int heightMode = MeasureSpec.getMode(heightMeasureSpec);
    int specWidth = MeasureSpec.getSize(widthMeasureSpec);
    int specHeight = MeasureSpec.getSize(heightMeasureSpec);
    if (getChildCount() > 0) {
      View child = getChildAt(0);
      if (widthMode == MeasureSpec.EXACTLY) {
        specHeight = (int) (specWidth * relativeSize);
        heightMeasureSpec = MeasureSpec.makeMeasureSpec(specHeight, MeasureSpec.EXACTLY);
      } else if (heightMode == MeasureSpec.EXACTLY) {
        specWidth = (int) (specHeight * relativeSize);
        widthMeasureSpec = MeasureSpec.makeMeasureSpec(specWidth, MeasureSpec.EXACTLY);
      }
      setMeasuredDimension(specWidth, specHeight);
      child.measure(widthMeasureSpec, heightMeasureSpec);
    }
  }

  @Override
  protected void onLayout(boolean changed, int l, int t, int r, int b) {
    if (getChildCount() > 0) {
      getChildAt(0).layout(0, 0, getRight(), getBottom());
    }
  }

}
